package org.syx.edl.validate;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * @author:whh
 * @date: 2025-09-05 22:14
 * <p></p>
 */
public class HibernateValidatorManager {

    // 私有静态实例，使用volatile确保多线程下的可见性
    private static volatile HibernateValidatorManager instance;

    // 验证器工厂（重量级资源）
    private ValidatorFactory validatorFactory;

    // 验证器实例
    private Validator validator;

    // 私有构造方法，防止外部实例化
    private HibernateValidatorManager() {
        // 初始化验证器工厂和验证器
        validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    /**
     * 双重检查锁获取单例实例
     * 保证线程安全且高效
     */
    public static HibernateValidatorManager getInstance() {
        if (instance == null) {
            synchronized (HibernateValidatorManager.class) {
                if (instance == null) {
                    instance = new HibernateValidatorManager();
                }
            }
        }
        return instance;
    }

    /**
     * 执行对象验证
     * @param object 待验证的对象
     * @return 验证结果集合
     */
    public <T> Set<ConstraintViolation<T>> validate(T object) {
        return validator.validate(object);
    }

    /**
     * 关闭验证器工厂，释放资源
     * 建议在应用退出时调用
     */
    public void shutdown() {
        if (validatorFactory != null) {
            validatorFactory.close();
        }
    }

    /**
     * 防止反序列化破坏单例
     */
    private Object readResolve() {
        return getInstance();
    }
}
